﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace AmuTools.Normal
{
    public class DatePathHelper
    {
        private static string GetDatePath()
        {
            DateTime now = DateTime.Now;
            string time_path = now.Year.ToString() + "/" + now.Month.ToString() + "-" + now.Day.ToString() + "/";

            string con_path = "/resource/" + time_path;

            return con_path;
        }

        /// <summary>
        /// 得到包含日期的文件名
        /// </summary>
        /// <param name="extension">文件扩展名</param>
        /// <returns></returns>
        private static string GetRandomFilePath(string extension)
        {
            return GetDatePath() + HashHelper.RandomHash_32() + extension;
        }

        /// <summary>
        /// 保存二进制数据为文件
        /// </summary>
        /// <param name="extension">文件扩展名</param>
        /// <param name="bytes">二进制字节数组</param>
        /// <returns></returns>
        public static string SaveFile(string extension, byte[] bytes)
        {
            string path = GetRandomFilePath(extension);

            string full_con_path = AppDomain.CurrentDomain.BaseDirectory + path;

            FileInfo fileInfo = new FileInfo(full_con_path);

            if(!fileInfo.Directory.Exists)
            {
                fileInfo.Directory.Create();
            }

            // 创建一个文件流
            FileStream fs = new FileStream(full_con_path, FileMode.Create);

            //将byte数组写入文件中
            fs.Write(bytes, 0, bytes.Length);
            //所有流类型都要关闭流，否则会出现内存泄露问题
            fs.Close();

            return path;
        }
    }
}
